package net.tng.strutsEjb.struts.ejbInjection;

import javax.ejb.EJB;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * 
 * @author nnguyen
 *
 */
public class ServiceLocator {

    private static final String EJB_JNDI_NAME_BEGIN = "java:app/strutsEjb-ejb/";

    /**
     * <p>
     * Searches for an EJB proxy object. The @EJB annotation must have a "name"
     * attribute.
     * <p>
     * Used by RequestProcessors or TilesProcessors (via InjectionHelper class).
     * 
     * @param <T>
     * @param cls
     *            the field type for the EJB to be injected
     * @param annotation
     *            the @EJB annotation at the field type
     * @return
     * @throws NamingException
     * @see #setNamingStrategy(JndiNamingStrategy)
     */
    public static <T> T getBean(Class<T> cls, EJB annotation)
            throws NamingException {

        final String jndiName;

        if ((annotation != null) && (annotation.name() != null)
                && (annotation.name().length() > 0)) {

            jndiName = EJB_JNDI_NAME_BEGIN + annotation.name();

            @SuppressWarnings("unchecked")
            T bean = (T) jndiLookup(jndiName);
            return bean;

        } else {
            throw new NamingException(
                    "Name attribut is required for EJB Look up");
        }
    }

    private static Object jndiLookup(String name) throws NamingException {
        // not every app server can reuse contexts, so we create a new one with
        // each call:
        InitialContext ctx = new InitialContext();
        return ctx.lookup(name);
    }

}
